/**
 * 维护表情库（用于聊天时发送）
 */
import { getLogger, Service } from '@gnlab/utils'
import { MemSubject } from '@gnlab/utils/rx'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

const logger = getLogger('services/resources/emotions')

export interface Emotion {
  id: number
  file: string
}

export class Emotions extends Service<Services> {
  private get auth() {
    return this.services.auth
  }

  registered() {
    void this.auth.accountId.then(() => {
      void this.load()
    })
  }

  private readonly _list = new MemSubject<Emotion[]>([])
  list = this._list.asStream()

  async load() {
    const resp = await API<Emotion[]>('/Emotion/GetEmotions')
    if (resp.success) {
      this._list.next(resp.data)
    } else {
      logger.warn('表情列表加载失败', resp.error)
    }
  }

  async add(file: string) {
    const resp = await API('/Emotion/AddEmotion', { data: { file }, formatter() {} })
    if (resp.success) {
      void this.load()
    } else {
      logger.warn(`表情添加失败：${resp.error}`)
    }
    return resp
  }

  async remove(id: number) {
    const resp = await API('/Emotion/RemoveEmotion', { data: { id }, formatter() {} })
    if (resp.success) void this.load()
    else logger.warn(`表情删除失败：${resp.error}`)
    return resp
  }
}
